/**
    Copyright (C) 2011  Alexander Vollmer

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.jefb.service.impl;

import org.jefb.entity.dto.FileToken;
import org.jefb.entity.dto.TransmissionCallback;
import org.jefb.sec.entity.AgentPermissions;
import org.jefb.sec.service.ITransInitService;
import org.jefb.service.INIOService;
import org.jefb.service.IReceiverService;
import org.jefb.util.service.impl.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ReceiverService implements IReceiverService {
	
	private static Logger log = LoggerFactory.getLogger(ReceiverService.class);
	
	//services
	@Autowired
	private INIOService nioService;
	@Autowired
	private ITransInitService transInitService;
	@Autowired
	private Config config;

	public TransmissionCallback receive(FileToken fileToken) {
		System.out.println("file token received:" + fileToken.getFilename()
				+ "|offset:" + fileToken.getOffset() + "|length:"
				+ fileToken.getLength());
		
		TransmissionCallback transmissionCallback = new TransmissionCallback();
		
		//check agent permissions
		AgentPermissions checkAgent = transInitService.checkAgent(fileToken.getSenderAgentId(), fileToken.getSessionId());
		if(checkAgent.isSessionRegistered()){
			transmissionCallback.getMessages().add("Session doesn't exists.");
			transmissionCallback.setTransmissionSucceed(false);
			return transmissionCallback;
		}
		
		FileToken checkedToken = transInitService.checkToken(fileToken);
		
		//check rights
		nioService.writeToken(checkedToken, transmissionCallback);
		if(transmissionCallback.getMessages().size()==0){
			transmissionCallback.setTransmissionSucceed(true);
		}
		try {
			Thread.sleep(5000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return transmissionCallback;
	}

	public void setNioService(INIOService nioService) {
		this.nioService = nioService;
	}

	public INIOService getNioService() {
		return nioService;
	}

	public void setTransInitService(ITransInitService transInitService) {
		this.transInitService = transInitService;
	}

	public ITransInitService getTransInitService() {
		return transInitService;
	}

	public void setConfig(Config config) {
		this.config = config;
	}

	public Config getConfig() {
		return config;
	}

}
